﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using BusinessEntity;
using BusinessRule;
using BusinessRule.Organization;
using learun.util;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using Nacos.AspNetCore;
using ProjectManApi.Extensions;
using ProjectManApi.mmm;

namespace ProjectManApi.Controllers
{
    public class UploadController : MvcControllerBase
    {

        private readonly IOperator _operator;
        private readonly IHttpContextAccessor _iHttpContextAccessor;

        private readonly JWTConfig jwtConfig;

        //添加Nacos 中间件
        private readonly INacosServerManager _serverManager;

        public UploadController(IOperator ioperator, IHttpContextAccessor iHttpContextAccessor, IOptions<JWTConfig> ijwtConfig, INacosServerManager iserverManager)
        {
            _operator = ioperator;
            _iHttpContextAccessor = iHttpContextAccessor;

            jwtConfig = ijwtConfig.Value;

            _serverManager = iserverManager;
        }

        #region 附件上传类

        public class RootArg
        {
            /// <summary>
            /// 
            /// </summary>
            public List<FilesItem> files { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public string bucketName { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public string callbackUrl { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public string code { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public string extra { get; set; }
        }

        public class FilesItem
        {
            /// <summary>
            /// 
            /// </summary>
            public int fileSize { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public string md5 { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public string original { get; set; }
        }

        //接收参数
        public class RootRes
        {
            /// <summary>
            /// 
            /// </summary>
            public int code { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public Data data { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public string message { get; set; }
        }

        public class Data
        {
            /// <summary>
            /// 
            /// </summary>
            public int chunkSize { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public string code { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public string extra { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public List<FilesItemRes> files { get; set; }
        }


        public class FilesItemRes
        {
            /// <summary>
            /// 
            /// </summary>
            public List<ChunksItem> chunks { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public int chunksToBeUploaded { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public string code { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public string extra { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public string fileName { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public int id { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public string original { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public int totalChunks { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public int uploadStatus { get; set; }
        }


        public class ChunksItem
        {
            /// <summary>
            /// 
            /// </summary>
            public int chunkNumber { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public string uploadUrl { get; set; }
        }
        #endregion


        #region 新
        //如果好用，请收藏地址，帮忙分享。

        //前段传进来
        public class RootRecQD
        {
            /// <summary>
            /// 
            /// </summary>
            public List<FilesItemNew> files { get; set; }
        }

        public class RootRecNew
        {
            /// <summary>
            /// 
            /// </summary>
            public string bucketName { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public string callbackUrl { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public List<FilesItemNew> files { get; set; }
        }
        public class FilesItemNew
        {
            /// <summary>
            /// 
            /// </summary>
            public int fileSize { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public string md5 { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public string original { get; set; }
        }





       
        public class RootResNew
        {
            /// <summary>
            /// 
            /// </summary>
            public int code { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public DataNew data { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public string message { get; set; }
        }
        public class DataNew
        {
            /// <summary>
            /// 
            /// </summary>
            public int chunkSize { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public List<FilesItemResNew> files { get; set; }
        }

        public class FilesItemResNew
        {
            /// <summary>
            /// 
            /// </summary>
            public List<ChunksItemResNew> chunks { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public int chunksToBeUploaded { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public string fileName { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public int id { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public string original { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public int totalChunks { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public int uploadStatus { get; set; }
        }


        //如果好用，请收藏地址，帮忙分享。
        public class ChunksItemResNew
        {
            /// <summary>
            /// 
            /// </summary>
            public int chunkNumber { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public string uploadUrl { get; set; }
        }

        #endregion


        [HttpPost]
        [AllowAnonymous]
        public async Task<IActionResult> FileUploadNew(RootRecNew fileLists)
        {
            fileLists.bucketName = "";
            fileLists.callbackUrl = "";

            var baseUrl = _serverManager.GetServerAsync("ic-auth").GetAwaiter().GetResult(); ;

            if (string.IsNullOrWhiteSpace(baseUrl))
            {
                //await RespondWithJson(httpContext.Response, new ResParameter { code = ResponseCode.exception, info = "授权服务节点全挂了" });
                return Fail("服务异常");
            }

            //http://118.190.140.38:4053/mock/29/file/upload

            var url = $"{baseUrl}/mock/29/file/upload";

            using (HttpClient client = new HttpClient())
            {

                url = url.Replace("172.31.162.64:3000", "118.190.140.38:4053");


                var data = Encoding.UTF8.GetBytes(fileLists.ToJson());
                var content = new ByteArrayContent(data);
                content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");

                var response = await client.PostAsync(url, content);


                //获取请求到数据，并转化为字符串
                var result = response.Content.ReadAsStringAsync().Result;
                var Jresult = Newtonsoft.Json.JsonConvert.DeserializeObject<RootResNew>(result);// result.ToJson();

                if (!string.IsNullOrWhiteSpace(Jresult.code.ToString()) && Jresult.code != 200)
                {
                    //await RespondWithJson(httpContext.Response, new ResParameter { code = ResponseCode.nologin, info = Jresult.error_description });
                    return Fail(Jresult.message);
                }

                return Success(Jresult);
            }

        }

        [HttpPost]
        [AllowAnonymous]
        public async Task<IActionResult> FileUpload(RootArg fileLists)
        {

            var baseUrl = _serverManager.GetServerAsync("ic-auth").GetAwaiter().GetResult(); ;

            if (string.IsNullOrWhiteSpace(baseUrl))
            {
                //await RespondWithJson(httpContext.Response, new ResParameter { code = ResponseCode.exception, info = "授权服务节点全挂了" });
                return Fail("服务异常");
            }

            //http://118.190.140.38:4053/mock/29/upload/callback
            //http://118.190.140.38:4053/mock/29/upload

            var url = $"{baseUrl}/mock/29/upload";

            using (HttpClient client = new HttpClient())
            {

                url = url.Replace("172.31.162.64:3000", "118.190.140.38:4053");


                var data = Encoding.UTF8.GetBytes(fileLists.ToJson());
                var content = new ByteArrayContent(data);
                content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");

                var response = await client.PostAsync(url, content);


                //获取请求到数据，并转化为字符串
                var result = response.Content.ReadAsStringAsync().Result;
                var Jresult = Newtonsoft.Json.JsonConvert.DeserializeObject<RootRes>(result);// result.ToJson();

                if (!string.IsNullOrWhiteSpace(Jresult.message))
                {
                    //await RespondWithJson(httpContext.Response, new ResParameter { code = ResponseCode.nologin, info = Jresult.error_description });
                    return Fail(Jresult.message);
                }

                return Success(Jresult);
            }

        }

    }
}